package cn.bellychang.leetcode.question203.cl01forcecrack;

/**
 * {@link:https://leetcode.com/problems/remove-linked-list-elements/}
 * @author: bellychang
 * @date: 2020/2/12
 */
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

class LinkedList{
    private ListNode dummyHead;

    public LinkedList(int[] arr) {
        dummyHead = new ListNode(-1);
        for (int i = 0; i < arr.length; i++) {
            addLast(new ListNode(arr[i]));
        }
    }

    public ListNode getFirst() {
        return dummyHead.next;
    }

    private void addLast(ListNode node) {
        ListNode temp = dummyHead.next;
        if (temp == null) {
            dummyHead.next = node;
        } else {
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = node;
        }
    }

    public static String display(ListNode head) {
        StringBuilder builder = new StringBuilder();
        ListNode temp = head;
        while (temp != null) {
            builder.append(temp.val)
                    .append("->");
            temp = temp.next;
        }
        return builder.length() >= 2 ? builder.toString().substring(0, builder.length() - 2) : builder.toString();
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }

    @Override
    public String toString() {
        return String.valueOf(val);
    }
}

/**
 * force crack
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        // this dummy head will not affect the linked list
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;
        ListNode prevNode = dummyNode;
        ListNode currentNode = head;
        while (currentNode != null) {
            if (currentNode.val == val) {
                prevNode.next = currentNode.next;
                currentNode = currentNode.next;
            } else {
                prevNode = prevNode.next;
                currentNode = currentNode.next;
            }
        }
        return dummyNode.next;
    }

    public static void main(String[] args) {

        LinkedList linkedList = new LinkedList(new int[]{1, 2, 6, 3, 4, 5, 6});
        System.out.println(LinkedList.display(linkedList.getFirst()));
        ListNode listNode = new Solution().removeElements(linkedList.getFirst(), 6);
        System.out.println(LinkedList.display(listNode));
    }
}
